package com.hrzyit.base.data.net

import com.hrzyit.base.common.BaseConstant
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Retrofit 工厂类，单例
 * @author YangWei
 * @date 2019/3/21
 */
open class RetrofitFactory private constructor() {

    companion object {
        // 单例模式工厂
        val instance: RetrofitFactory by lazy { RetrofitFactory() }
    }

    private val retrofit: Retrofit

    // 常用拦截器
    private val interceptor: Interceptor

    init {
        // 通用拦截
        interceptor = Interceptor {
                chain ->
            // 添加常用请求头信息
            val req = chain.request().newBuilder()
                .addHeader("Content-Type", "application/json")
                .addHeader("charset", "UTF-8")
                .build()
            chain.proceed(req)
        }

        // Retrofit 实例化
        retrofit = Retrofit.Builder()
            .baseUrl(BaseConstant.SERVER_ADDRESS)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(initClient())
            .build()
    }

    /**
     * OKHttp创建
     */
    private fun initClient(): OkHttpClient {
        // 构建 Retrofit 使用的 Client
        return OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addInterceptor(initInterceptor())
            .connectTimeout(10, TimeUnit.SECONDS) // 设置连接超时时间
            .readTimeout(10, TimeUnit.SECONDS) // 设置读取超时时间
            .build()
    }

    /**
     * 日志拦截器
     */
    private fun initInterceptor(): Interceptor {
        // 构建日志拦截器
        val interceptor = HttpLoggingInterceptor()
        // 设置日志级别
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return interceptor
    }

    /**
     * 具体服务实例化
     */
    fun <T> create(service:Class<T>):T {
        return retrofit.create(service)
    }
}